<?php
/**
 *
 *
 *
 */
class Yz_Form_Element_UploadImage
    extends Yz_Form_Element_Abstract
{

    protected $name;
    protected $value = 0;
    protected $fileName = "";

    /** the model which will handle the upload;
     *      can be set using modelName config, or determined as 'Upload'+this.name
     *  @var Yz_Model_Interface
     */
    protected $model;
    /** the onwer module of the model which will handle the upload
     *      can be set using moduleName config, or the owner module of this.form
     *  @var Yz_Module_Interface
     */
    protected $module;


    /**
     *  @param array $values
     *  @return chainable
     */
    public function findValue(Yz_Class $values)
    {
        $name = $this->name;
        if ($values->offsetExists($name)) {
            $fileName = $name . '_fileName';
            if ($values->offsetExists($fileName)) {
                $this->value = $values[$name];
                $this->fileName = $values[$fileName];
            } else {
                debug("Key {$fileName} is missing, value not set");
            }
        }
        return $this;
    }

    /**
     *
     */
    public function render(Yz_Template_Interface $template)
    {
        $curValOutput = $this->renderCurrentValue();
        $elName       = $this->name;
        $action       = $template->webPrefix
            . $template->YzAdmin
            . $this->getUploadAction()
        ;
        $cssClass     = $this->getCSSClass();
        $buttonTitle  = $template->translate($elName.':Upload');
        $buttonUpload = $template->translate('Upload');
        $buttonCancel = $template->translate('Cancel');
        $o = <<<html
            <div id="yz-upload-{$elName}" class="{$cssClass}">
                <input type="hidden" name="{$elName}" value="{$this->value}" />
                <div class="yz-upload-value">{$curValOutput}</div>
                <a href="{$action}" title="{$buttonTitle}"
                    onclick="var self=this; Yz.loadClass('Yz.Upload', function() {
                        Yz.Upload
                            .createUpload('{$elName}')
                            .setUploadAction('{$action}')
                            .showDialog({
                                title:  '{$buttonTitle}',
                                upload: '{$buttonUpload}',
                                cancel: '{$buttonCancel}'
                            })
                        ;
                    });
                    return false">{$buttonUpload}</a>
            </div>\n
html;
        return $o;
    }


    /**
     *  @return this
     *  @throw Yz_Form_Element_Exception
     */
    public function parse(Yz_Hash $values)
    {
        $elName = $this->name;
        debug("Element '$elName'");
        $value = $values[$elName];
        $value = Yz_Int::valueOf($value);
        if (null === $value) {
            throw new Yz_Form_Element_Exception("Invalid value for element {$elName} (must be an integer number)");
        }
        $this->value = $value;
        return $this;
    }

    /** get the module - owner of the upload model
     *      try config 'moduleName' or use the form's owner module
     *  @return Yz_Module_Interface
     */
    protected function getModule()
    {
        $module =& $this->module;
        if (! $module) {
            $config = $this->element->moduleName;
            if (! $config) {
                $module = $this->form->getModule();
            } else {
                $module = \Yz::selectModule($config);
            }
        }
        return $module;
    }

    /** get upload model: try config 'modelName'
     *      or derive the modelName as 'Upload'+this.name
     *  @return Yz_Model_Interface
     */
    protected function getModel()
    {
        $model =& $this->model;
        if (! $model) {
            $config = $this->element->modelName;
            if (! $config) {
                $config = 'Upload' . ucfirst($this->name);
            }
            $model = $this->getModule()->selectModel($config);
        }
        return $model;
    }


    protected function getUploadAction()
    {
        $m = $this->getModel();
        $a = $m::UPLOAD_CONTROLLER;
        $a = \Yz_String::fromCamelCase(
            $this->getModule()->getName()
            . '/'
            . lcfirst($a)
        );
        return $a;
    }

    /**
     *
     */
    protected function getUploadPath()
    {
        $path = $this->getModel()->getUploadPath();
        return $path;
    }

    /**
     *
     */
    protected function renderCurrentValue()
    {
        $o = <<<html
html;
        $fileName = $this->fileName;
        if ("" !== $fileName) {
            $uploadPath = $this->getUploadPath();
            $o .= <<<html
                <a href='{$uploadPath}{$fileName}'>{$fileName}</a>
html;
        }
        return $o;
    }

}
